<template>
    <div>
        <ul>
            <li>
                <h3>全局自定义指令</h3>
            </li>
            <li>
                <label>
                    <span>账号：</span>
                    <input @input="changeColor" v-model="form.name" type="text" />
                </label>
            </li>
            <li>
                <label>
                    <span>密码：</span>
                    <input @input="changeColor" v-model="form.password" type="password" />
                </label>
            </li>
            <li>
                <button v-color="color" @click="handleClick">改变颜色</button>
            </li>
        </ul>
        <button v-myDirective="textColor" @focus="handleFouces" @blur="handleBlur">局部自定义指令</button>

    </div>
</template>

<script setup>
import { ref } from 'vue';

const color = ref({ color: '#ffffff', backgroundColor: 'rgba(153, 153, 153, 0.5)' });
const form = ref({
    name: '',
    password: ''
});
let flag = false;
// 全局自定义指令：表单填写完整时，按钮颜色变化
const changeColor = () => {
    // 切换颜色
    const keys = Object.keys(form.value);
    flag = keys.map((v) => form.value[v]).filter(Boolean).length == keys.length;
    if (flag) {
        color.value = { color: '#FFF', backgroundColor: '#56bdb8' };
    } else {
        color.value = { color: '#ffffff', backgroundColor: 'rgba(153, 153, 153, 0.5)' };
    }
};
const handleClick = () => {
    if (!flag) return console.log('表单填写完整');
    console.log('handleClick');
};

// 局部自定义指令：焦点变化时，改变文字颜色
const textColor = ref('#333');
const vMyDirective = {
    beforeMount: (el, binding) => {
        // 在元素上做些操作
        el.style.color = binding.value;
    },
    mounted: (el, binding) => {
        // 在元素上做些操作
        el.style.color = binding.value;
    },
    updated: (el, binding) => {
        // 在元素上做些操作
        el.style.color = binding.value;
    }
};
const handleFouces = () => {
    textColor.value = '#389893';
};
const handleBlur = () => {
    textColor.value = '#333';
};
</script>
<style lang="scss" scoped>
li {
    margin-bottom: 10px;
}

button {
    transition: color 0.5s;
    border: 1px solid transparent;
}
</style>